'''
Author: @zhyy
Date: 2021-01-27 14:23:32
LastEditors: @zhyy
LastEditTime: 2021-02-07 17:07:14
'''
#coding:UTF-8
import time,datetime
def time_to_timestamp(t):
    '''
    description:将格式化字符串时间转换为时间戳
    param {str t 格式化字符串时间}
    return float timestamp
    '''
    #将时间转换成时间数组
    try:
        timeArray = time.strptime(t, "%Y-%m-%d %H:%M:%S")

    except:
        timeArray = time.strptime(t, "%Y-%m-%dT%H:%M:%S")
    #转换成时间戳
    timestamp = ('%f'%time.mktime(timeArray))
    return timestamp

def get_now_time():
    '''
    description: 获取当前时间格式化:2021-01-31 16:19:13
    param {*}
    return list [float:时间戳,str:格式化时间字符串] [time_stamp,now_time]
    '''
    time_stamp=time.time()
    now_time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time_stamp))
    return now_time

# 将时间戳转换为秒级时间字符串
def timestamp_to_timestr(time_stamp):
    '''
    description: 把时间戳转换为格式化时间对象
    param {*}
    return str timestr
    '''
    if len(str(time_stamp))==13:
        time_stamp = float(time_stamp)/1000
    else:
        time_stamp=float(time_stamp)
    timestr=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time_stamp))
    return timestr
#------------------------------------------------------------------------------

# 获取毫秒级时间
def get_timef():
    s = datetime.datetime.now()
    timestr = datetime.datetime.strptime(str(s),'%Y-%m-%d %H:%M:%S.%f')
    return timestr
    
# 毫秒级时间转换为时间戳
def timef_to_timestamp(timestr):
    timestr=str(timestr)
    datetime_obj = datetime.datetime.strptime(timestr, "%Y-%m-%d %H:%M:%S.%f")
    ret_stamp = int(time.mktime(datetime_obj.timetuple()) * 1000.0 + datetime_obj.microsecond / 1000.0)
    return ret_stamp
    
# 将毫秒级时间戳转换为毫秒级时间字符串
def timestamp_to_timefstr(t):
    timeStamp = float(t)/1000
    ret_datetime = datetime.datetime.utcfromtimestamp(timeStamp).strftime("%Y-%m-%d %H:%M:%S.%f")
    return ret_datetime
